"use client";

import { Button, message, Row } from "antd";
import { MdSaveAs } from "react-icons/md";
import { IoMdRefreshCircle } from "react-icons/io";
import { VscError } from "react-icons/vsc";
import SignaturePad from "react-signature-pad-wrapper";
import { useRef } from "react";
import { base64ToBlob } from "../../utils/publicFuc";
import { UploadSign } from "@/app/api/operation/interview";
import { getUserAccount } from "../../utils/defender";

export interface SignPropType {
  docid: string;
  flow_code: string;
  flow_phase: string;
  seq: number;
  onCancel: () => void;
  onSubmit: () => void;
}

export default function Sign(props: SignPropType) {
  const signaturePadRef: any = useRef(null);

  const Submit = async () => {
    if(signaturePadRef.current.isEmpty()){
        message.info('您還沒有簽名，請確認！')
        return false
    }
    const file = base64ToBlob(
      signaturePadRef.current.toDataURL() as string,
      "image/png"
    );
    try {
      const res: any = await UploadSign(
        file,
        props.docid,
        props.flow_code,
        getUserAccount() as string,
        props.seq.toString()
      );
      if (res === "success") {
        message.success("上傳成功");
        Clear()
        props.onSubmit();
      }
    } catch {
      message.error("上傳錯誤");
    }
  };

  const Clear = () => {
    if (signaturePadRef.current) {
      signaturePadRef.current.clear();
    }
  };
  const Cancle = () => {
    if (signaturePadRef.current) {
      signaturePadRef.current.clear();
    }
    props.onCancel();
  };
  return (
    <div>
      <h4 style={{ margin: "5px 0", color: "black" }}>
        {props.flow_phase}
      </h4>
      <div
        style={{
          width: "500px",
          height: "250px",
          background: "#fff",
          margin: "0 auto",
        }}
      >
        <SignaturePad
          ref={signaturePadRef}
          options={{ penColor: "rgb(18, 18, 18)" }}
          width={500}
          height={250}
        />
      </div>
      <Row style={{ marginTop: "20px", textAlign: "center" }}>
        <Button
          icon={<MdSaveAs></MdSaveAs>}
          color="default"
          style={{ marginLeft: "30px" }}
          onClick={() => {
            Submit();
          }}
        >
          上傳
        </Button>
        <Button
          icon={<IoMdRefreshCircle></IoMdRefreshCircle>}
          type="primary"
          style={{ marginLeft: "30px" }}
          onClick={() => Clear()}
        >
          重簽
        </Button>
        <Button
          onClick={() => Cancle()}
          icon={<VscError></VscError>}
          type="primary"
          danger
          style={{ marginLeft: "30px" }}
        >
          取消
        </Button>
      </Row>
    </div>
  );
}
